﻿@{
    Layout = null;
}

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <title>新增订单</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
    <script src="//unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/element-plus/dist/locale/zh-cn.min.js"></script>
    <style>
        .basicInfo {
            width: 82%;
            height: 600px;
            background-color: #fff;
            padding-top: 20px;
            margin-top:30px;
            margin-left:20px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .stockUpDetail {
            width: 82%;
            min-height: 530px;
            background-color: #fff;
            padding-top: 10px;
            margin-left:20px;
            margin-top: 50px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .uploadAttachment{
            width: 82%;
            min-height: 450px;
            background-color: #fff;
            padding-top: 10px;
            margin-left:20px;
            margin-top: 50px;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .saveBlock{
            display: grid;
            place-items: center;
            position: sticky;
            bottom: 0;
            width:100%;
            height:60px;
            background-color:#fff;
            z-index:20;
            box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        }

        .titleH {
            margin-left: 40px;
        }

        .orderTable {
            margin: 0 auto;
            width: 80%;
            border-spacing: 0 40px;
        }

        .imp {
            color: red;
        }

        .orderTable tbody tr td {
            border-spacing: 0 20px;
        }

        .custom-readonly-input .el-input__inner {
            background-color: #f0f0f0 !important;
            padding: 0px;
        }

        .custom-readonly-input .el-input__wrapper {
            background-color: #f0f0f0 !important;
        }

        /* 树控件样式优化 */
        .el-tree {
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            padding: 10px;
            max-height: 400px;
            overflow-y: auto;
        }

        .tree-title {
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }

        .detailBlock {
            padding-left: 30px;
        }

        .uploadAttach{
            padding-top:30px;
            padding-left:60px;
        }

        .searchBlock {
            display: inline;
        }

        .buttonBlock {
            display: inline;
            margin-left: 335px;
        }

        /* 合计行样式优化 */
        .el-table__footer-wrapper {
            font-weight: bold;
            background-color: #f5f7fa;
        }

        .el-table__footer-wrapper td {
            text-align: center !important;
        }
        .promptWord{
            color:#606266;
        }

        .upload-demo{
            display:inline-block;
        }
        .btnBlock{
            margin-left:auto;
            padding:10px 20px 10px 10px;
        }

        .pagination-container {
            margin-left:45%;
        }

        .valueV{
            color:orangered;
            font-weight:bolder;
        }
    </style>
</head>
<body>
    <div id="app" class="common-layout">
        <div class="basicInfo">
            <h2 class="titleH">基础信息</h2>
            <hr />
            <div class="basicInfoForm">
                <table class="orderTable">
                    <tbody>
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;进货单号
                            </td>
                            <td>
                                <el-input type="text" v-model="purchaseOrderCode" style="width:80%;" readonly placeholder="自动生成单号"></el-input>
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;进货日期
                            </td>
                            <td>
                                <el-date-picker type="date"
                                                placeholder="请选择日期"
                                                style="width:80%;"
                                                v-model="purchaseDate"
                                    value-format="YYYY-MM-DD"/>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;供应商
                            </td>
                            <td>
                                <el-select placeholder="请选择"
                                           style="width:80%;"
                                           v-model="selectedSupplierId"
                                           v-on:change ="handleSupplierChange">
                                    <el-option v-for="supplier in supplierList"
                                               :key="supplier.supplierId"
                                               :label="supplier.supplierName"
                                               :value="supplier.supplierId" />
                                </el-select>
                                <el-button style="border:0px;color:limegreen">设置</el-button>
                            </td>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系人
                            </td>
                            <td>
                                <el-input placeholder="请输入" v-model="contactPerson" readonly style="width:80%;" class="custom-readonly-input"></el-input>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;联系方式
                            </td>
                            <td>
                                <el-input placeholder="请输入" v-model="contactPhone" readonly style="width:80%;" class="custom-readonly-input"></el-input>
                            </td>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;进货部门
                            </td>
                            <td v-on:click="stockInDepart = true">
                                <el-input placeholder="请选择"
                                          v-model="selectedDepart"
                                          style="width:80%"
                                          readonly></el-input>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <span class="imp">*</span>&nbsp;&nbsp;&nbsp;进货人
                            </td>
                            <td v-on:click="openManModal">
                                <el-input placeholder="请选择"
                                          v-model="selectedManName"
                                          style="width:80%"
                                          readonly></el-input>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;备注
                            </td>
                            <td colspan="3">
                                <el-input v-model="remarks" type="textarea" rows="5" placeholder="请输入" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="stockUpDetail">
            <h2 class="titleH">进货明细</h2>
            <hr />
            <div class="detailBlock">
                <div class="addAndRemove">
                    <el-button type="success" v-on:click="openAddGoodsDialog">添加</el-button>&nbsp;&nbsp;&nbsp;
                    <el-button type="danger" v-on:click="removeGoodsDetail">移除</el-button>
                </div>
                <div class="detailTable">
                    <el-table :data="goodsDetailData"
                              style="width: 1600px; margin-top: 10px"
                              v-on:selection-change="handleSelectionChange('detail', $event)"
                              ref="detailTable"
                              stripe>
                        <el-table-column fixed type="selection" width="50"></el-table-column>
                        <el-table-column fixed prop="id" label="序号" width="70"></el-table-column>
                        <!-- 货品名称：对应goodsName -->
                        <el-table-column fixed prop="goodsName" label="货品名称" width="100"></el-table-column>
                        <!-- 货品编号：对应goodsCode -->
                        <el-table-column fixed prop="goodsCode" label="货品编号" width="150"></el-table-column>
                        <!-- 规格型号：对应specification -->
                        <el-table-column prop="specification" label="规格型号" width="100"></el-table-column>
                        <!-- 单位：对应unit -->
                        <el-table-column prop="unit" label="单位" width="80">吨</el-table-column>
                        <!-- 货品类型：对应category -->
                        <el-table-column prop="goodsTypeName" label="货品类型" width="120"></el-table-column>
                        <!-- 当前库存：对应availableInventoryQty -->
                        <el-table-column prop="availableInventoryQty" label="当前库存" width="100" :formatter="formatNumber"></el-table-column>
                        <!-- 货品数量：手动输入 -->
                        <el-table-column prop="purchaseQuantity" label="货品数量" width="120">
                            <template #default="scope">
                                <el-input v-model.number="scope.row.purchaseQuantity"
                                          placeholder="请输入数量"
                                          style="width: 100%"
                                          v-on:input ="handleNumberInput('purchaseQuantity', scope.row)"
                                          v-on:blur="validateNumber('purchaseQuantity', scope.row)"
                                  clearable></el-input>
                            </template>
                        </el-table-column>
                        <!-- 进货单价：对应purchaseReferencePrice -->
                        <el-table-column prop="purchasePrice" label="进货单价(元)" width="120">
                            <template #default="scope">
                                <el-input v-model.number="scope.row.purchasePrice"
                                          placeholder="请输入单价"
                                          style="width: 100%"
                                          v-on:input ="handleNumberInput('purchasePrice', scope.row)"
                                          v-on:blur="validateNumber('purchasePrice', scope.row)"
                                  clearable
                                ></el-input>
                            </template>
                        </el-table-column>
                        <!-- 金额：自动计算 -->
                        <el-table-column prop="amount" label="金额" width="120" :formatter="formatNumber"></el-table-column>
                        <!-- 备注 -->
                        <el-table-column prop="remarks" label="备注" width="200">
                            <template #default="scope">
                                <el-input type="textarea"
                                          v-model="scope.row.remarks"
                                          placeholder="请输入备注"
                                          :rows="3"
                                          style="width: 100%"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" min-width="180">
                            <template #default="scope">
                                <el-button class="operate-btn"
                                           link type="primary" size="default"
                                           v-on:click="removeDetail(scope.row)">
                                    移除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="fixed-full-row" style="border-bottom:1px solid #f0f0f0;height:28px;padding:10px 0px">
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="promptWord">合计</span>
                        <div class="countNum" style="display:inline-block;margin-left:900px">
                            <span class="promptWord">货品种类: <span class="valueV">{{ totalCategories }}</span></span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span class="promptWord">货品数量: <span class="valueV">{{ totalQuantity }}</span>吨</span>&nbsp;&nbsp;&nbsp;&nbsp;
                            <span class="promptWord">总金额: <span class="valueV">{{ formatNumber(null, null, totalAmount) }}</span>元</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="uploadAttachment">
            <h2 class="titleH">上传附件</h2>
            <hr />
            <div class="uploadAttach">
                <!-- 文件选择组件（仅负责选择，不上传） -->
                <el-upload class="upload-demo"
                           action=""
                           name="files"
                           :file-list="tempFileList"
                           :auto-upload="false"
                           :show-file-list="false"
                           accept=".doc,.docx,.pdf,.rar,.zip"
                           :limit="10"
                           :on-exceed="handleFileExceed"
                           :on-change="handleFileSelect">
            <el-button type="primary">选择文件</el-button>
        </el-upload>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <span class="promptWord">支持格式：doc,docx,pdf,rar,zip | 单个文件≤200MB | 最多10个文件</span>

                <!-- 自定义文件列表（仅显示文件名） -->
                <div class="attachmentFile" style="margin-top: 20px;">
                    <div v-for="(file, index) in tempFileList"
                         :key="file.uid"
                         class="file-item"
                         style="width:60%;display: flex; align-items: center; margin: 10px 0; padding: 8px; border: 1px solid #eee; border-radius: 4px;">
                        <span style="flex: 1;">{{ file.name }}</span>
                        <el-button size="small"
                                   type="text"
                                   style="color: #ff4d4f;"
                                   v-on:click ="removeTempFile(index)">
                            删除
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
        <div class="saveBlock">
            <div class="btnBlock">
                <el-button v-on:click="closeDetail">关闭</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveAsDraft">保存草稿</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button v-on:click="saveAndAdd">保存并新增</el-button>
                &nbsp;&nbsp;&nbsp;&nbsp;<el-button type="success" v-on:click="saveThis">保存</el-button>
            </div>
        </div>

        @* 进货部门选择模态框（增加搜索功能）*@
        <el-dialog v-model="stockInDepart" :modal="false" style="width:400px">
            <h3>选择部门</h3>
            <hr/>
            <br/>
            <!-- 部门搜索框 -->
            <el-input v-model="departSearchKey"
                      placeholder="请输入部门名称搜索"
                      class="search-input"
                      clearable>
                <template #prefix>
                    <el-icon class="el-input__icon"><Search /></el-icon>
                </template>
            </el-input>
            <br />
            <br />
            <div class="tree-container">
                <el-tree style="max-width: 300px"
                         :data="filteredDepartData"
                         :props="defaultProps"
                         :expand-on-click-node="true"
                         :default-expanded-keys="defaultExpandedKeys"
                         v-on:node-click="departNode" />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="stockInDepart = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmDepart">确定</el-button>
                </div>
            </template>
        </el-dialog>

        @* 选择进货人员模态框（增加搜索功能）*@
        <el-dialog v-model="stockInMan" :modal="false" style="width:400px">
            <h3>选择人员</h3>
            <hr />
            <br/>
            <!-- 人员搜索框 -->
            <el-input v-model="manSearchKey"
                      placeholder="请输入人员姓名搜索"
                      class="search-input"
                      clearable>
                <template #prefix>
                    <el-icon class="el-input__icon"><Search /></el-icon>
                </template>
            </el-input>
            <br />
            <h3>所属部门：{{ selectedOrgName || '未选择部门' }}</h3>
            <el-select v-model="selectedMan"
                       placeholder="请选择人员"
                       style="width: 100%"
                       v-on:change="confirmMan">
                <el-option v-for="man in searchFilteredManData"
                           :key="man.usersId"
                           :label="man.usersTrueName"
                           :value="man.usersId">
                </el-option>
            </el-select>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="stockInMan = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmMan">确定</el-button>
                </div>
            </template>
        </el-dialog>

        @* 添加货品模态框 *@
        <el-dialog v-model="addGoodsDialog" :modal="false" style="width:1000px">
            <h3>添加货品</h3>
            <div class="addDetailsMain">
                <!-- 搜索区域 -->
                <div class="searchBlock">
                    <el-input type="text"
                              placeholder="请输入货品编号/名称"
                              style="width:300px"
                              v-model="goodsSearchKey"
                              clearable
                              v-on:keyup.enter="searchGoods">
                    </el-input>
                </div>
                <div class="buttonBlock">
                    <el-button v-on:click="resetGoodsSearch">重置</el-button>
                    <el-button type="success" v-on:click="searchGoods">查询</el-button>
                </div>

                <!-- 货品表格 -->
                <div class="goodsDetailTable">
                    <el-table :data="paginatedGoodsData"
                              style="width: 100%; margin-top: 10px"
                              v-on:selection-change="handleSelectionChange('add', $event)"
                              ref="addTable"
                              stripe>
                        <el-table-column type="selection" width="50"></el-table-column>
                        <!-- 序号列：自动计算（当前页-1）*页大小 + 索引 + 1 -->
                        <el-table-column label="序号" width="70">
                            <template #default="scope">
                                {{ (goodsCurrentPage - 1) * goodsPageSize + scope.$index + 1 }}
                            </template>
                        </el-table-column>
                        <!-- 货品编号 -->
                        <el-table-column prop="goodsCode" label="货品编号" width="130"></el-table-column>
                        <!-- 货品名称 -->
                        <el-table-column prop="goodsName" label="货品名称" width="150"></el-table-column>
                        <!-- 规格型号 -->
                        <el-table-column prop="specification" label="规格型号" width="130"></el-table-column>
                        <!-- 单位 -->
                        <el-table-column prop="unit" label="单位" width="80">吨</el-table-column>
                        <!-- 入库单价 -->
                        <el-table-column prop="purchaseReferencePrice"
                                         label="入库单价(元)"
                                         width="120"
                                         :formatter="formatNumber">
                        </el-table-column>
                        <!-- 当前库存 -->
                        <el-table-column prop="availableInventoryQty"
                                         label="当前库存(吨)"
                                         width="100"
                                         :formatter="formatNumber">
                        </el-table-column>
                    </el-table>
                    <!-- 分页组件（核心修改：与主页面分页逻辑对齐） -->
                    <div class="pagination-container" style="margin-top: 16px;">
                        <el-pagination v-model:current-page="goodsCurrentPage"
                                       v-model:page-size="goodsPageSize"
                                       :page-sizes="[10, 20, 50, 100]"
                                       :total="goodsTotal"
                                       layout="total, sizes, prev, pager, next, jumper"
                                       v-on:size-change="handleGoodsPageSizeChange"
                                       v-on:current-change="handleGoodsPageChange">
                        </el-pagination>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="addGoodsDialog = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmAddGoods">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, onMounted, computed, watchEffect } = Vue;
        const { ElMessageBox, ElMessage, ElNotification, ElIcon, Search } = ElementPlus;
        const app = createApp({
            components: {
                ElIcon,
                Search
            },
            setup() {
                // 模态框控制变量
                const stockInDepart = ref(false);
                const stockInMan = ref(false);
                const addGoodsDialog = ref(false);

                const purchaseDate = ref('');

                // 选择结果变量
                const selectedDepart = ref('');
                const selectedMan = ref('');
                const selectedManName = ref('');
                const currentDepart = ref(null);
                // 存储当前选中的部门名称（用于显示）
                const selectedOrgName = ref('');

                // 存储当前选中部门的OrgId（用于过滤人员）
                const selectedDepartOrgId = ref(null);
                const defaultExpandedKeys = ref([1]);
                // 存储所有部门的扁平列表（方便人员选择后快速匹配部门）
                const flatDepartList = ref([]);
                const filteredManData = ref([]);
                const selectedManId = ref(''); // 进货人ID（BuyerBy）

                // 新增：搜索关键词
                const departSearchKey = ref(''); // 部门搜索关键词
                const manSearchKey = ref('');    // 人员搜索关键词

                // 供应商相关变量
                const supplierList = ref([]); // 存储所有供应商
                const selectedSupplierId = ref(''); // 选中的供应商ID
                const contactPerson = ref(''); // 联系人
                const contactPhone = ref(''); // 联系方式

                const saveBtnDisabled = ref(false);

                const remarks = ref('');

                // 1. 从sessionStorage获取当前用户ID（键为usersId）
                const getCurrentUserId = () => {
                    // 1. 从 sessionStorage 读取存储的 user JSON 字符串
                    const userStr = sessionStorage.getItem('YH');
                    if (!userStr) {
                        ElMessage.warning('未检测到登录状态，请重新登录');
                        return '';
                    }

                    try {
                        // 2. 解析 JSON 字符串为对象
                        const userObj = JSON.parse(userStr);
                        // 3. 提取 usersId（兼容可能的空值）
                        const userId = userObj?.id?.toString() || '';

                        if (!userId) {
                            ElMessage.warning('用户信息不完整，请重新登录');
                        }
                        return userId;
                    } catch (error) {
                        // 处理 JSON 解析失败的异常（如格式错误）
                        console.error('解析用户信息失败：', error);
                        ElMessage.error('用户信息异常，请重新登录');
                        return '';
                    }
                };

                //当前登录用户Id
                const currentUserId = ref(getCurrentUserId());

                //货品信息
                // 货品数据相关
                // 货品分页参数
                const goodsCurrentPage = ref(1); // 当前页码
                const goodsPageSize = ref(10);   // 每页条数
                const allGoodsData = ref([]);    // 存储全部货品原始数据（一次性加载）
                const goodsSearchKey = ref('');  // 搜索关键词
                const selectedGoods = ref([]);   // 已选中的货品
                const addTable = ref(null);


                // 部门相关逻辑
                const departData = ref([]);
                const defaultProps = ref({
                    children: 'children',
                    label: 'label'
                });

                //日期
                const validateDate = () => {
                    if (!purchaseDate.value) {
                        ElMessage.warning('请选择进货日期');
                        return false;
                    }
                    // 可以添加日期范围校验，例如不能选择未来日期
                    const today = new Date().toISOString().split('T')[0];
                    if (purchaseDate.value > today) {
                        ElMessage.warning('进货日期不能选择未来日期');
                        return false;
                    }
                    return true;
                };

                // 在保存时调用日期验证（示例）
                const saveOrder = () => {
                    // 先验证日期
                    if (!validateDate()) return;

                    // 其他保存逻辑...
                    ElMessage.success('订单保存成功');
                };

                // 新增：部门搜索过滤（递归过滤树结构）
                const filteredDepartData = computed(() => {
                    if (!departSearchKey.value) return departData.value;
                    const keyword = departSearchKey.value.toLowerCase();

                    // 递归过滤部门树
                    const filterTree = (nodes) => {
                        return nodes
                            .filter(node => {
                                // 匹配当前节点名称
                                const matchSelf = node.name?.toLowerCase().includes(keyword) ||
                                                node.label?.toLowerCase().includes(keyword);
                                // 递归匹配子节点
                                const filteredChildren = filterTree(node.children || []);
                                // 保留有匹配子节点的父节点
                                return matchSelf || filteredChildren.length > 0;
                            })
                            .map(node => ({
                                ...node,
                                // 递归处理子节点
                                children: filterTree(node.children || [])
                            }));
                    };

                    return filterTree(departData.value);
                });

                const departNode = (data) => {
                    currentDepart.value = data;
                    selectedDepartOrgId.value = data.id;
                    departData.value.forEach(node => {
                        node.highlight = node.id === data.id;
                    });
                };

                const confirmDepart = () => {
                    if (currentDepart.value) {
                        selectedDepart.value = currentDepart.value.label;
                        selectedDepartOrgId.value = currentDepart.value.id;
                        // 新增：同步更新部门名称显示
                        selectedOrgName.value = currentDepart.value.label;

                        filteredManData.value = manData.value.filter(man => {
                            return man && String(man.orgId) === String(selectedDepartOrgId.value);
                        });
                        selectedMan.value = '';
                        selectedManName.value = '';
                    } else {
                        selectedDepart.value = '';
                        selectedDepartOrgId.value = null;
                        // 新增：未选择部门时清空显示
                        selectedOrgName.value = '';
                        filteredManData.value = manData.value;
                        ElMessage.info('未选择部门，将显示所有人员');
                    }
                    stockInDepart.value = false;
                };

                //人员相关开始-----------------------------------------------------------------

                // 人员相关逻辑
                const manData = ref([]);

                // 新增：人员搜索过滤（先按部门过滤，再按关键词过滤）
                const searchFilteredManData = computed(() => {
                    if (!manSearchKey.value) return filteredManData.value;
                    const keyword = manSearchKey.value.toLowerCase();
                    return filteredManData.value.filter(man => {
                        return man.usersTrueName?.toLowerCase().includes(keyword);
                    });
                });

                const confirmMan = () => {
                    if (selectedMan.value) {
                        const selectedManObj = manData.value.find(man => {
                            return man && man.usersId && String(man.usersId) === String(selectedMan.value);
                        });

                        if (!selectedManObj) {
                            ElMessage.error('未找到匹配的人员，请刷新页面重试');
                            stockInMan.value = false;
                            return;
                        }
                        selectedManId.value = selectedMan.value;
                        const manOrgId = selectedManObj.orgId;
                        if (!manOrgId) {
                            ElMessage.error('人员部门信息异常');
                            stockInMan.value = false;
                            return;
                        }

                        const matchedDepart = flatDepartList.value.find(depart => {
                            return depart && depart.orgId && String(depart.orgId) === String(manOrgId);
                        });

                        if (matchedDepart) {
                            selectedDepart.value = matchedDepart.label;
                            // 新增：通过人员所属部门更新显示名称
                            selectedOrgName.value = matchedDepart.label;

                            selectedDepartOrgId.value = manOrgId;
                            filteredManData.value = manData.value.filter(man =>
                                man && man.orgId && String(man.orgId) === String(manOrgId)
                            );
                            selectedManName.value = selectedManObj.usersTrueName;
                        } else {
                            ElMessage.error('未找到匹配的部门，请刷新页面重试');
                        }

                        stockInMan.value = false;
                    } else {
                        ElMessage.warning('请选择人员');
                    }
                };

                const openManModal = () => {
                    // 打开模态框时，强制同步部门名称
                    selectedOrgName.value = selectedDepart.value || '';
                    stockInMan.value = true;
                };

                //人员相关结束-----------------------------------------------------------------

                //供应商部分开始------------------------------------------------------------
                // 新增：加载供应商数据
                const loadSuppliers = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetSupplierInfoForSelectTable');
                        // 确保返回的是数组
                        if (Array.isArray(res.data)) {
                            supplierList.value = res.data;
                        } else {
                            ElMessage.warning('供应商数据格式异常');
                            supplierList.value = [];
                        }
                    } catch (err) {
                        console.error('加载供应商失败：', err);
                        ElMessage.error('网络错误，无法加载供应商数据');
                        supplierList.value = [];
                    }
                };

                // 新增：处理供应商选择变化
                const handleSupplierChange = (supplierId) => {
                    // 查找选中的供应商
                    const selectedSupplier = supplierList.value.find(
                        item => item.supplierId === supplierId
                    );

                    if (selectedSupplier) {
                        // 填充联系人和联系方式
                        contactPerson.value = selectedSupplier.contactPerson || '';
                        contactPhone.value = selectedSupplier.contactPhone || '';
                    } else {
                        // 未找到对应供应商时清空
                        contactPerson.value = '';
                        contactPhone.value = '';
                    }
                };
                //供应商部分结束------------------------------------------------------------

                const purchaseOrderCode = ref('');
                const params = { ruleId: 6 };
                function getPurchaseOrderCode(){
                        axios.post(`/NumberingRules/GenerateByRuleId?ruleId=${params.ruleId}`)
                    .then(res => {
                        if (res.data && res.data.success) {
                            purchaseOrderCode.value = res.data.number;
                        } else {
                            ElMessage({ type: 'error', message: '获取进货单号失败：' + (res.data?.message || '未知错误') });
                        }
                    })
                    .catch(err => {
                        console.error('获取进货单号接口请求失败：', err);
                        ElMessage({ type: 'error', message: '网络错误，无法获取进货单号' });
                    });
                }
                getPurchaseOrderCode();

                const detailData = ref([]);

                //货品信息部分开始------------------------------------------------------------------------
                // 货品分页参数（与主页面分页变量命名风格一致）
                

                // 计算属性：总记录数（基于筛选后的数据长度）
                const filteredGoodsData = computed(() => {
                    if (!goodsSearchKey.value.trim()) return allGoodsData.value;
                    // 搜索逻辑：匹配货品编号或名称
                    const keyword = goodsSearchKey.value.trim().toLowerCase();
                    return allGoodsData.value.filter(item =>
                        (item.goodsCode?.toLowerCase().includes(keyword) || false) ||
                        (item.goodsName?.toLowerCase().includes(keyword) || false)
                    );
                });

                // 计算属性：总记录数
                const goodsTotal = computed(() => filteredGoodsData.value.length);

                // 计算属性：分页后的数据（前端切片）
                const paginatedGoodsData = computed(() => {
                    const start = (goodsCurrentPage.value - 1) * goodsPageSize.value;
                    const end = start + goodsPageSize.value;
                    return filteredGoodsData.value.slice(start, end);
                });

                // 加载货品数据（一次性加载全部，后续分页在前端处理）
                const loadGoodsData = async () => {
                    try {
                        const res = await axios.get('/StockUpOrder/GetAllGoodsInfoForAddGoods');
                        if (res.data) {
                            allGoodsData.value = res.data|| []; // 存储全部数据
                            goodsCurrentPage.value = 1; // 重置页码
                        } else {
                            ElMessage.warning('未获取到货品数据');
                            allGoodsData.value = [];
                        }
                    } catch (err) {
                        console.error('加载货品失败：', err);
                        ElMessage.error('网络错误，无法加载货品信息');
                    }
                };

                // 页码改变事件（纯前端切换）
                const handleGoodsPageChange = (val) => {
                    goodsCurrentPage.value = val;
                    // 清除选中状态（与主页面逻辑一致）
                    if (addTable.value) {
                        addTable.value.clearSelection();
                        selectedGoods.value = [];
                    }
                };

                // 页大小改变事件（重置页码）
                const handleGoodsPageSizeChange = (val) => {
                    goodsPageSize.value = val;
                    goodsCurrentPage.value = 1; // 页大小改变时重置为第一页
                };

                // 搜索货品（纯前端筛选）
                const searchGoods = () => {
                    goodsCurrentPage.value = 1; // 搜索时重置页码
                };

                // 重置搜索条件
                const resetGoodsSearch = () => {
                    goodsSearchKey.value = '';
                    goodsCurrentPage.value = 1;
                };

                // 打开添加货品模态框
                const openAddGoodsDialog = () => {
                    addGoodsDialog.value = true;
                    loadGoodsData(); // 打开时加载全部货品数据
                };

                // 确认添加货品（更新属性映射）
                const confirmAddGoods = () => {
                    if (selectedRows.add.value.length === 0) {
                        ElMessage.warning("请先勾选要添加的货品");
                        return;
                    }

                    // 1. 提取已存在的货品编码，建立编码到明细行的映射（便于快速查找）
                    const existingGoodsMap = new Map(); // key: goodsCode, value: 明细行对象
                    goodsDetailData.value.forEach(item => {
                        existingGoodsMap.set(item.goodsCode, item);
                    });

                    // 2. 分离重复货品和新货品
                    const duplicateGoods = []; // 已存在的货品
                    const newGoods = [];       // 新货品

                    selectedRows.add.value.forEach(goods => {
                        if (existingGoodsMap.has(goods.goodsCode)) {
                            duplicateGoods.push(goods);
                        } else {
                            newGoods.push(goods);
                        }
                    });

                    // 3. 处理重复货品（合并数量）
                    if (duplicateGoods.length > 0) {
                        const duplicateNames = duplicateGoods.map(g => g.goodsName).join('、');

                        // 询问用户是否合并数量
                        ElMessageBox.confirm(
                            `以下货品已在明细中：${duplicateNames}，是否将数量合并到现有行？`,
                            '重复提示',
                            {
                                confirmButtonText: '合并数量',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }
                        ).then(() => {
                            // 合并重复货品的数量（默认添加1，可根据实际需求调整）
                            duplicateGoods.forEach(goods => {
                                const existingItem = existingGoodsMap.get(goods.goodsCode);
                                // 累加数量（这里默认每次添加1，若有输入框可改为对应值）
                                existingItem.purchaseQuantity = (existingItem.purchaseQuantity || 0) + 1;
                                // 重新计算金额（数量变化后）
                                existingItem.amount = (existingItem.purchaseQuantity * existingItem.purchasePrice).toFixed(2) * 1;
                            });

                            // 同时添加新货品
                            addNewGoods(newGoods);

                            // 关闭弹窗并清理选择
                            finishAddOperation();
                        }).catch(() => {
                            // 用户取消，不执行任何操作
                        });
                        return;
                    }

                    // 4. 无重复时直接添加新货品
                    addNewGoods(newGoods);
                    finishAddOperation();
                };

                // 抽取添加新货品的逻辑（复用）
                const addNewGoods = (goodsList) => {
                    goodsList.forEach(goods => {
                        goodsDetailData.value.push({
                            id: goodsDetailData.value.length + 1,
                            goodsName: goods.goodsName,
                            goodsCode: goods.goodsCode,
                            specification: goods.specification,
                            unit: goods.unit || '吨',
                            goodsTypeName: goods.goodsTypeName || '',
                            availableInventoryQty: goods.availableInventoryQty || 0,
                            goodsTypeId: goods.goodsTypeId || 0,
                            purchaseQuantity: 1, // 默认添加1个，可改为用户输入值
                            purchasePrice: goods.purchaseReferencePrice || 0,
                            amount: goods.purchaseReferencePrice || 0,
                            remarks: ''
                        });
                    });
                };

                // 抽取添加完成后的操作（复用）
                const finishAddOperation = () => {
                    const totalAdded = selectedRows.add.value.length;
                    ElMessage.success(`已处理 ${totalAdded} 种货品`);
                    addGoodsDialog.value = false;
                    if (addTable.value) {
                        addTable.value.clearSelection();
                        selectedRows.add.value = [];
                    }
                };

                const formatNumber = (row, column, cellValue) => {
                    if (cellValue === null || cellValue === undefined || isNaN(Number(cellValue))) {
                        return '0.00';
                    }
                    return Number(cellValue).toFixed(2);
                };


                //货品信息部分结束------------------------------------------------------------------------

                watchEffect(() => {
                    detailData.value.forEach(row => {
                        if (row) {
                            const qty = row.operator || 0;
                            const price = row.totalQuantity || 0;
                            row.totalAmount = (qty * price).toFixed(2) * 1;
                        }
                    });
                    // 当打开人员模态框时，如果已有选中部门，同步显示部门名称
                    if (stockInMan.value) {                       
                        selectedOrgName.value = selectedDepart.value || '';
                    }
                })


                
                // 明细数据（与货品表格属性对应）
                const goodsDetailData = ref([]);

                // 计算合计值
                const totalCategories = computed(() => {
                    // 货品种类数（去重统计）
                    const codes = new Set();
                    goodsDetailData.value.forEach(item => codes.add(item.goodsCode));
                    return codes.size;
                });

                const totalQuantity = computed(() => {
                    // 货品总数量
                    return goodsDetailData.value.reduce((sum, item) => {
                        return sum + (Number(item.purchaseQuantity) || 0);
                    }, 0);
                });

                const totalAmount = computed(() => {
                    // 总金额
                    return goodsDetailData.value.reduce((sum, item) => {
                        return sum + (Number(item.amount) || 0);
                    }, 0);
                });
                    
                // 实时过滤非数字输入（只保留数字和小数点）
                const handleNumberInput = (field, row) => {
                    if (row[field] === null || row[field] === undefined) return;
                    // 转换为字符串处理，过滤非数字和非小数点字符
                    let value = row[field].toString().replace(/[^\d.]/g, '');
                    // 限制只能有一个小数点
                    value = value.replace(/\.{2,}/g, '.');
                    // 去掉小数点前的前导零（可选，根据需求保留）
                    value = value.replace(/^0+(\d)/, '$1');
                    // 如果以小数点开头，自动补0
                    if (value.startsWith('.')) value = '0' + value;
                    // 转换回数字（空值处理为0）
                    row[field] = value === '' ? 0 : Number(value);
                };

                // 失焦时验证是否为非负数
                const validateNumber = (field, row) => {
                    const value = row[field];
                    // 空值或非数字处理为0
                    if (value === null || value === undefined || isNaN(Number(value))) {
                        row[field] = 0;
                        ElMessage.warning(`${field === 'purchaseQuantity' ? '数量' : '单价'}不能为空，已自动设为0`);
                        return;
                    }
                    // 负数处理为0并提示
                    if (Number(value) < 0) {
                        row[field] = 0;
                        ElMessage.warning(`${field === 'purchaseQuantity' ? '数量' : '单价'}不能为负数，已自动设为0`);
                    }
                    // 保留两位小数（根据业务需求调整）
                    row[field] = Number(Number(value).toFixed(2));
                };

                // 监听数量和单价变化，自动计算金额
                watchEffect(() => {
                    goodsDetailData.value.forEach(row => {
                        if (row) {
                            const qty = Number(row.purchaseQuantity) || 0;
                            const price = Number(row.purchasePrice) || 0;
                            row.amount = (qty * price).toFixed(2) * 1;
                        }
                    });
                });

                //进货明细开始-----------------------------------------------------------------------------

                const selectedRows = {
                    detail: ref([]),
                    add: ref([])
                };

                const handleSelectionChange = (tableType, val) => {
                    selectedRows[tableType].value = val;
                };

                const removeDetail = (row) => {
                    const newData = goodsDetailData.value.filter(item => item.id !== row.id);
                    goodsDetailData.value = newData;
                    setTimeout(() => ElMessage.success("已移除当前进货明细行"), 0);
                };
                
                const removeGoodsDetail = () => {
                    if (selectedRows.detail.value.length === 0) {
                        ElMessage.warning("请先勾选要移除的明细行");
                        return;
                    }
                    const removeCount = selectedRows.detail.value.length;
                    goodsDetailData.value = goodsDetailData.value.filter(
                        row => !selectedRows.detail.value.some(selected => selected.id === row.id)
                    );
                    selectedRows.detail.value = [];
                    setTimeout(() => ElMessage.success(`已批量移除 ${removeCount} 条明细`), 0);
                };

                //进货明细结束-----------------------------------------------------------------------------

    // 附件上传部分开始------------------------------------------------------------------------------------

                // 核心变量：暂存选择的文件（无编号，后端生成）
                const tempFileList = ref([]);
                // 已上传成功的附件信息（用于提交给订单接口）
                const uploadedAttachments = ref([]);
                // 后端接口地址（统一使用订单提交接口，无需单独上传接口）
                const orderApiUrl = '/StockUpOrder/AddOmPurchaseOrderInfo';

                // 选择文件后暂存到临时列表（合并重复的handleFileChange和handleFileSelect）
                const handleFileSelect = (file, fileList) => {
                    tempFileList.value = fileList; // 同步临时文件列表
                };

                // 移除暂存的文件（保留一个实现）
                const removeTempFile = (index) => {
                    tempFileList.value.splice(index, 1);
                    ElMessage.info('已移除选中文件');
                };

                // 处理文件超出限制（合并重复的handleFileExceed和handleExceed）
                const handleFileExceed = (files) => {
                    ElMessage.warning(`最多只能上传10个文件，本次超出${files.length}个`);
                };

                // 处理上传失败（通用失败提示）
                const handleUploadError = (err, file) => {
                    ElMessage.error(`文件 "${file.name}" 上传失败，请重试`);
                };

                // 附件额外参数（与后端DTO对应，从进货人获取创建人信息）
                const attachmentExtraData = computed(() => ({
                    createBy: currentUserId.value || '未知用户', // 替换硬编码，从选中的进货人ID获取
                    createTime: new Date().toISOString().split('T')[0], // 当前日期（YYYY-MM-DD）
                    updateBy: '0',
                    updateTime: new Date().toISOString().split('T')[0]
                }));

                // 手动上传附件（整合到订单提交流程，无需单独上传接口）
                const uploadAttachments = async () => {
                    if (tempFileList.value.length === 0) {
                        // 无附件时直接返回成功（若后端允许无附件，可删除此判断）
                        return { success: true, data: [] };
                    }

                    // 构建FormData（包含文件和额外参数）
                    const formData = new FormData();
                    // 添加额外参数
                    const extraData = attachmentExtraData.value;
                    Object.keys(extraData).forEach(key => {
                        formData.append(key, extraData[key]);
                    });
                    // 添加文件
                    tempFileList.value.forEach(file => {
                        formData.append('files', file.raw); // 原生文件对象
                    });

                    try {
                        // 调用后端接口（直接使用订单提交接口，或单独的附件上传接口）
                        const response = await axios.post(orderApiUrl, formData, {
                            headers: { 'Content-Type': 'multipart/form-data' }
                        });
                        if (response.data.success) {
                            uploadedAttachments.value = response.data.data || [];
                            ElMessage.success(`成功上传 ${tempFileList.value.length} 个附件`);
                            return { success: true, data: uploadedAttachments.value };
                        } else {
                            ElMessage.error(`附件上传失败：${response.data.message}`);
                            return { success: false };
                        }
                    } catch (err) {
                        console.error('附件上传异常：', err);
                        ElMessage.error('附件上传失败，请重试');
                        return { success: false };
                    }
                };

                // 移除已上传的文件（若需要在上传后删除）
                const removeUploadedFile = (index) => {
                    const removedFile = uploadedAttachments.value.splice(index, 1)[0];
                    ElMessage.info(`文件 "${removedFile.name}" 已从上传列表中删除`);
                };

    // 附件上传部分结束------------------------------------------------------------------------------------

                function closeDetail(){
                    window.location.href = '/StockUpOrder/Index';
                }
                
                //保存为草稿
                async function saveAsDraft(){
                        // 基础验证
                        if (!purchaseOrderCode.value) {
                            ElMessage.warning('请先获取进货单号');
                            return;
                        }
                        if (!selectedSupplierId.value) {
                            ElMessage.warning('请选择供应商');
                            return;
                        }
                        if (!selectedManId.value) {
                            ElMessage.warning('请选择进货人');
                            return;
                        }
                        // if (tempFileList.value.length === 0) {
                        //     ElMessage.warning('请至少上传一个附件'); 后端要求必须上传文件
                        //     return;
                        // }

                        //保存为草稿时允许不添加明细
                        // if (goodsDetailData.value.length === 0) {
                        //     ElMessage.warning('请添加进货明细');
                        //     return;
                        // }

                        // 构建FormData（严格匹配后端接口参数）
                        const formData = new FormData();

                        // 3. 复杂对象：序列化为JSON字符串（关键！后端将手动解析）
                        const opof = {
                            UpOrderNo: purchaseOrderCode.value,
                            SupplierId: selectedSupplierId.value,
                            OrderStatus: '0', // 确保字段值类型与后端一致（如字符串/数字）
                            BuyerBy: selectedManId.value,
                            CreateBy: currentUserId.value,
                            Remarks: remarks.value
                        };
                        const opodf = {
                                Details: goodsDetailData.value.map((item, index) => ({
                                UpOrderId: 0,
                                GoodsCode: item.goodsCode || '',
                                GoodsTypeId: item.goodsTypeId || 0,
                                PurchaseUnitPrice: Number(item.purchasePrice) || 0,
                                OrderQuantity: Number(item.purchaseQuantity) || 0,
                                AttachmentCode: '无',
                                Remarks: item.remarks || '无'
                            }))
                        };
                        // 字段名与后端新参数名保持一致
                        formData.append('opofStr', JSON.stringify(opof));
                        formData.append('opodfStr', JSON.stringify(opodf));
                        // 1. 附件文件（正常传递）
                        if (tempFileList.value.length > 0) {
                            tempFileList.value.forEach(file => {
                                formData.append('files', file.raw); // 原生文件对象，后端能自动解析为List<IFormFile>
                            });
                            const now = new Date().toISOString(); // 传递完整ISO格式
                            formData.append('createBy', currentUserId.value);
                            formData.append('updateBy', '0');
                        }


                        // 4. 提交请求（无需手动设置Content-Type，浏览器自动处理multipart/form-data）
                        try {
                            const response = await axios.post(orderApiUrl, formData); // 移除自定义headers！

                            if (response.data.success) {
                                ElMessage.success('订单保存成功');
                                    axios.post(`/NumberingRules/UpdateMaxAfterSuccess?ruleId=${6}&currentSerial=${3}`)
                                    .then(res=>{
                                        getPurchaseOrderCode()
                                        ElMessage.success('订单号已更新')
                                        window.scrollTo({
                                            top: 0,
                                            behavior: 'smooth' // 平滑滚动
                                        });
                                    })
                                    .catch(err=>{
                                        Console.log(err)
                                    })
                            } else {
                                ElMessage.error(`保存失败：${response.data.message || '未知错误'}`);
                            }
                        } catch (err) {
                            console.error('提交异常：', err);
                            ElMessage.error('网络错误，请重试');
                        }
                }

                //保存
                const saveThis = async () => {
                    // 基础验证
                    if (!purchaseOrderCode.value) {
                        ElMessage.warning('请先获取进货单号');
                        return;
                    }
                    if (!selectedSupplierId.value) {
                        ElMessage.warning('请选择供应商');
                        return;
                    }
                    if (!selectedManId.value) {
                        ElMessage.warning('请选择进货人');
                        return;
                    }
                    // if (tempFileList.value.length === 0) {
                    //     ElMessage.warning('请至少上传一个附件'); 后端要求必须上传文件
                    //     return;
                    // }
                    if (goodsDetailData.value.length === 0) {
                        ElMessage.warning('请添加进货明细');
                        return;
                    }
                    saveBtnDisabled.value = true;
                    // 构建FormData（严格匹配后端接口参数）
                    const formData = new FormData();

                    // 3. 复杂对象：序列化为JSON字符串（关键！后端将手动解析）
                    const opof = {
                        UpOrderNo: purchaseOrderCode.value,
                        SupplierId: selectedSupplierId.value,
                        OrderStatus: '1', // 确保字段值类型与后端一致（如字符串/数字）
                        BuyerBy: selectedManId.value,
                        CreateBy: currentUserId.value,
                        Remarks: remarks.value
                    };
                    const opodf = {
                            Details: goodsDetailData.value.map((item, index) => ({
                            UpOrderId: 0,
                            GoodsCode: item.goodsCode || '',
                            GoodsTypeId: item.goodsTypeId || 0,
                            PurchaseUnitPrice: Number(item.purchasePrice) || 0,
                            OrderQuantity: Number(item.purchaseQuantity) || 0,
                            AttachmentCode: '无',
                            Remarks: item.remarks || '无'
                        }))
                    };
                    // 字段名与后端新参数名保持一致（如opofStr）
                    formData.append('opofStr', JSON.stringify(opof));
                    formData.append('opodfStr', JSON.stringify(opodf));
                    // 1. 附件文件（正常传递）
                    if (tempFileList.value.length > 0) {
                        tempFileList.value.forEach(file => {
                            formData.append('files', file.raw); // 原生文件对象，后端能自动解析为List<IFormFile>
                        });
                        const now = new Date().toISOString(); // 传递完整ISO格式（如2024-10-22T12:00:00.000Z），后端DateTime可自动解析
                        formData.append('createBy', currentUserId.value);
                        formData.append('updateBy', '0');
                    }
                    

                    // 4. 提交请求（无需手动设置Content-Type，浏览器自动处理multipart/form-data）
                    try {
                        const response = await axios.post(orderApiUrl, formData); // 移除自定义headers！

                        if (response.data.success) {
                            ElMessage.success('订单保存成功');
                            setTimeout(() => {
                                saveBtnDisabled.value = false;
                            }, 3000);
                            axios.post(`/NumberingRules/GenerateAndUpdateNumber?ruleId=${6}`)
                            .then(res=>{
                                setTimeout(() => window.location.href = '/StockUpOrder/Index', 500);
                            })
                            .catch(err=>{
                                Console.log(err)
                            })
                        } else {
                            ElMessage.error(`保存失败：${response.data.message || '未知错误'}`);
                        }
                    } catch (err) {
                        console.error('提交异常：', err);
                        ElMessage.error('网络错误，请重试');
                    }
                };

                function saveAndAdd() {
                    // 确保 saveThis 是 Promise 并等待完成
                    saveThis().then(() => {
                        // 存储滚动标记
                        sessionStorage.setItem('needScrollToTop', 'true');
                        // 强制刷新（不使用缓存，确保页面重新渲染）
                        window.location.reload(true); // 关键：添加 true 参数
                    }).catch(err => {
                        console.error('保存失败', err);
                    });
                }


                // 初始化数据
                onMounted(async () => {
                    // 优先处理滚动标记
                    const needScroll = sessionStorage.getItem('needScrollToTop');
                    if (needScroll === 'true') {
                        // 方案1：同步滚动（最高优先级）
                        window.scrollTo(0, 0);

                        // 方案2：如果方案1失败，用延迟滚动兜底（兼容特殊浏览器）
                        setTimeout(() => {
                            window.scrollTo(0, 0);
                        }, 0);

                        // 清除标记
                        sessionStorage.removeItem('needScrollToTop');
                    }
                    try {
                        //加载供应商信息
                        await loadSuppliers();
                        // 设置默认日期为今天
                        const today = new Date().toISOString().split('T')[0];
                        purchaseDate.value = today;

                        //加载组织信息
                        const departRes = await axios.get('/StockUpOrder/GetOrgInfoForSelectTable');
                        departData.value = Array.isArray(departRes.data) ? departRes.data : [];
                        if (departData.value.length === 0) {
                            ElMessage.warning('部门数据为空，请检查接口');
                        }

                        const flattenDepart = (departArray) => {
                            let result = [];
                            departArray.forEach(depart => {
                                if (!depart) return;
                                const flatDepart = {
                                    orgId: depart.id || depart.orgId,
                                    label: depart.name || depart.label,
                                    children: Array.isArray(depart.children) ? depart.children : []
                                };
                                result.push(flatDepart);
                                if (flatDepart.children.length > 0) {
                                    result = [...result, ...flattenDepart(flatDepart.children)];
                                }
                            });
                            return result;
                        };
                        flatDepartList.value = flattenDepart(departData.value);
                    } catch (err) {
                        console.error('获取部门数据失败：', err);
                        ElMessage.error('网络错误，无法加载部门数据');
                        departData.value = [];
                        flatDepartList.value = [];
                    }

                    try {
                        const manRes = await axios.get('/StockUpOrder/GetUserInfoForSelectTable');
                        manData.value = (manRes.data || []).filter(man => man && man.usersId);
                        filteredManData.value = manData.value;
                        if (manData.value.length === 0) {
                            ElMessage.warning('未加载到有效人员数据');
                        }
                    } catch (err) {
                        console.error('获取人员数据失败：', err);
                        ElMessage.error('网络错误，无法加载人员数据');
                        manData.value = [];
                        filteredManData.value = [];
                    }
                });


                return {
                    //当前用户Id
                    currentUserId,
                    // 日期相关
                    purchaseDate,
                    validateDate,
                    saveOrder,

                    // 模态框和选择器相关
                    stockInDepart,
                    stockInMan,
                    addGoodsDialog,
                    selectedDepart,
                    selectedMan,
                    selectedManName,
                    departData,
                    manData,
                    defaultProps,
                    departNode,
                    confirmDepart,
                    confirmMan,
                    purchaseOrderCode,
                    getPurchaseOrderCode,
                    selectedDepartOrgId,
                    flatDepartList,
                    filteredManData,
                    openManModal,
                    selectedOrgName,
                    remarks,

                    // 供应商相关
                    supplierList,
                    selectedSupplierId,
                    contactPerson,
                    contactPhone,
                    handleSupplierChange,
                    defaultExpandedKeys,

                    // 货品相关
                    goodsCurrentPage,
                    goodsPageSize,
                    goodsTotal,
                    paginatedGoodsData,
                    goodsSearchKey,
                    loadGoodsData,
                    handleGoodsPageChange,
                    handleGoodsPageSizeChange,
                    searchGoods,
                    resetGoodsSearch,
                    openAddGoodsDialog,
                    confirmAddGoods,
                    formatNumber,
                    addTable,

                    // 计算相关
                    totalCategories,
                    totalQuantity,
                    totalAmount,
                    goodsDetailData,
                    handleNumberInput,
                    validateNumber,

                    // 明细操作相关
                    detailData,
                    removeGoodsDetail,
                    handleSelectionChange,
                    selectedRows,
                    removeDetail,

                    // 搜索相关
                    departSearchKey,
                    manSearchKey,
                    filteredDepartData,
                    searchFilteredManData,

                    // 附件相关（核心补充项）
                    tempFileList,
                    uploadedAttachments,
                    handleFileSelect,
                    removeTempFile,
                    handleFileExceed,
                    uploadAttachments,
                    removeUploadedFile,
                    attachmentExtraData,

                    // 保存相关
                    saveAsDraft,
                    saveThis,
                    closeDetail,
                    saveAndAdd,
                    saveBtnDisabled
                };
            }
        });
        app.use(ElementPlus, {
            locale: ElementPlusLocaleZhCn
        });
        app.mount('#app');
    </script>
</body>
</html>
